<template>
  <div class="statistics-linechart-comp">
    <div :class="className" :style="{ height: height, width: width }"></div>
  </div>
</template>
<script>
import echarts from "echarts";

export default {
  name: "statistics-linechart-comp",
  components: {},
  props: {
    className: {
      type: String,
      default: "chart",
    },
    width: {
      type: String,
      default: "100%",
    },
    height: {
      type: String,
      default: "350px",
    },
    chartData: {
      type: Object,
      required: true,
    },
    yAxisName: {
      type: String,
      default: "",
    },
    yAxisTitleStyle: {
      type: Object,
      required: false
    }
  },
  computed: {},
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        this.setOptions(val);
      },
      
    },
  },
  data() {
    return {
      chart: null,
    };
  },
  created() {},
  mounted() {
    this.$nextTick(() => {
      this.initChart();
    });

    window.addEventListener("resize", this.resize);
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.resize);

    if (this.chart) {
      this.chart.dispose();
      this.chart = null;
    }
  },
  methods: {
    resize() {
      this.chart.resize();
    },
    initChart() {
      this.chart = echarts.init(document.querySelector("." + this.className));
      this.setOptions(this.chartData);

      // 注册点击事件
      // this.chart.on("click", (params) => {
      //   if (params.componentType === "series") {
      //     // 点击到了数据点上
      //     this.$emit("dataPointClick", params.name);
      //   }
      // });
    },
    setOptions(chartData) {
      if (!chartData.x) return;
     
      this.chart.setOption({
        xAxis: {
          data: chartData.x,
          boundaryGap: false,
          axisTick: {
            show: false,
          },
        },
        yAxis: {
          name: this.yAxisName,
          nameTextStyle: this.yAxisTitleStyle,
          axisTick: {
            show: false,
          },
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            // type: "cross",
            // snap: true,
            label: {
              show: true,
              precision: 3, // 精确小数点位数
            },
          },
        },
        grid: {
          left: 35,
          right: 20,
          bottom: 20,
          top: 30,
          containLabel: true,
        },
        series: [
          {
            name: this.yAxisName,
            smooth: true,
            type: "line",
            data: chartData.y,
            animationDuration: 2800,
            animationEasing: "cubicInOut",
          },
        ],
      },false,true);
    },
  },
};
</script>
<style lang="scss" scoped>
.statistics-linechart-comp {
}
</style>
